﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;
using WMSSystem.YSL.Interfance;

namespace WMSSystem.Web
{
    /// <summary>
    /// JWT认证中间件
    /// </summary>
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next">下一个中间件</param>
        public JwtMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 中间件处理方法
        /// </summary>
        /// <param name="context">HTTP上下文</param>
        /// <returns>任务</returns>
        public async Task InvokeAsync(HttpContext context)
        {
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

            if (!string.IsNullOrEmpty(token))
            {
                var jwtService = context.RequestServices.GetService<IJwtService>();
                if (jwtService != null)
                {
                    var isValid = await jwtService.ValidateTokenAsync(token);
                    if (isValid)
                    {
                        var userId = jwtService.GetUserIdFromToken(token);
                        if (!string.IsNullOrEmpty(userId))
                        {
                            // 将用户ID添加到当前请求的上下文中
                            context.Items["UserId"] = userId;
                        }
                    }
                }
            }

            await _next(context);
        }
    }
}
